class Vue{
    constructor(props){
        this.init(props);
        this.virtualDOM();
    }
    
    init(props){
        this.el = props.el;
        this.data = props.data;
        this.flag = document.createDocumentFragment();
        observe(this.data, this);
        return this;
    }

    compile(node,parent){
        let par = parent;
        let reg = /\{\{(.*)\}\}/;
        switch(node.nodeType){
            //Element
            case 1:
                let attr = node.attributes;
                for(let i = 0; i < attr.length; i++){
                    if( attr[i].nodeName == 'v-model' ){
                        let name = attr[i].nodeValue;
                        let that = this;
                        node.addEventListener('input',function(e){
                            that.data[name] = e.target.value;
                        });
                        node.value = this.data[name];
                        node.removeAttribute('v-model');
                    }
                }
                if( node.childNodes.length > 0 ){
                    let tpar = document.createDocumentFragment();
                    tpar.append(node.cloneNode());
                    node.parentNode.removeChild(node);
                    let child;
                    while(child = node.firstChild){
                        this.compile(child,tpar.firstChild);
                    }
                    
                    par.append(tpar);
                }else{
                    par.append(node);
                }

            break;
            //Text
            case 3:
                // node.nodeValue = node.nodeValue.replace(/\s+/img,'').trim();
                if( reg.test(node.nodeValue) ){
                    let name = RegExp.$1;
                    name = name.trim();
                    node.nodeValue = node.nodeValue.replace(reg,this.data[name]);
                }
                par.append(node);
            break;
        }
        return par;
    }

    virtualDOM(){
        let node;
        let par = document.createDocumentFragment();
        while( node = document.querySelector(this.el).firstChild ){
            var a = this.compile(node,par);
        }
        document.querySelector(this.el).append(par);

        return this;
    }
}

function defineReactive(obj, key, val){
    Object.defineProperty(obj, key, {
        get(){
            return val
        },
        set(newVal){
            console.log(newVal)
            if(newVal === val)return;
            val = newVal;
            console.log(val);
        }
    })
}

function observe(obj){
    Object.keys(obj).forEach(function(key){
        defineReactive(obj, key, obj[key]);
    });
}



var vm = new Vue({
    el : '#app',
    data : {
        text:'绑定',
        title:'【TITLE!!!!】',
        content:'【JBL AUDIO】'
    }
});